import Types from '../types'
import DataStore from "../../expand/dao/DataStore"

/*
 *@Description: 获取最热数据的异步action
 *@param: storeName
 *@param: url
 *@param: pageSize
 *@return: {function(*=)}
 *@Author:  zhengLinPing
*/
export function onLoadPopularData(storeName,url,pageSize){
  
    return dispatch =>{
        dispatch({type:Types.POPULAR_REFRESH,storeName})
        let dataStroe = new DataStore()
        dataStroe.fetchData(url)
            .then(data=>{
                console.log(data)
                handleData(dispatch,storeName,data,pageSize)
            })
            .catch(error=>{
                console.log(error)
                dispatch({
                    type:Types.POPULAR_REFRESH_FAIL,
                    storeName,
                    error
                })
            })
    }
    
 

}
/*
 *加载更多
 *@param: storeName
 *@param: pageIndex 第几页
 *@param: pageSize  每页展示条数
 *@param: dataArray  原始数据
 *@param: callback  回调函数，可以通过回调函数来向页面通信：比如异常信息的展示，没有更多
 *@return: 
 *@Author:  zhengLinPing
*/

export function onLoadMorePopular(storeName,pageIndex,pageSize,dataArray=[],callback){
    return dispatch =>{
        setTimeout(()=>{
            if((pageIndex-1)*pageSize>=dataArray.length){
                if(typeof callback === 'function'){
                    callback('没有更多数据')
                }
                dispatch({
                    type:Types.POPULAR_LOAD_MORE_FAIL,
                    storeName,
                    error:'没有更多数据',
                    pageIndex:--pageIndex,
                    pageData:dataArray
                })
            }else{
                let max = pageIndex * pageSize > dataArray.length? dataArray.length : pageIndex * pageSize
                dispatch({
                    type:Types.POPULAR_LOAD_MORE_SUCCESS,
                    storeName,
                    pageIndex,
                    pageData:dataArray.slice(0,max)
                })
            }
        },500)
    }

}

function handleData(dispatch,storeName,data,pageSize){
    let fixItems = []
    if(data && data.data && data.data.items){
        fixItems = data.data.items.slice(0,pageSize)
    }
    
    dispatch({
        type:Types.POPULAR_REFRESH_SUCCESS,
        pageData:fixItems,
        items:data.data.items,
        pageIndex:1,
        storeName
    })
}